var casper = require('casper').create({   
	verbose: true, 
	logLevel: 'debug',
	pageSettings: {
         loadImages:  false,         // The WebPage instance used by Casper will
         loadPlugins: false,         // use these settings
         userAgent: 'Mozilla/5.0 (Windows NT 6.1; rv:17.0) Gecko/20100101 Firefox/17.0'
     }
 });
//phantom.outputEncoding="gbk";
var fs = require('fs');
casper.options.viewportSize = {width: 1680, height: 924};
var url = 'http://lz.book.sohu.com/book-26945.html';
var target = './世界如此险恶,你要内心强大2.txt'
casper.cache = {linkList:[]};
casper.start(url,function (argument) {
	// var hasJq = 
	var urls = this.evaluate(function() {
		var list = document.querySelectorAll('.lc_con1 ul li a');
		var urls = [];
		for (var i = 0; i < list.length; i++) {
			var link = list[i];
			var url = link.getAttribute('href');
			urls.push(url);
		}
		return urls;
	});

	this.cache.linkList = urls;
});

var ChapterNo = 0;
var recurve = function() {
	var urls = this.cache.linkList;
	url = urls[ChapterNo++];
	if(ChapterNo > urls.length){
		console.log('grab over!');
		this.exit();
	}else{
		url = 'http://lz.book.sohu.com' + url;
		grabChapter.call(this,url);
		this.run(recurve);
	}
};

function grabChapter (url) {
	this.start(url,function (argument) {
		var obj = this.evaluate(function() {
			var content = "",title = "",con,a=document.querySelector('.lc');
			if(a){
				con = a.querySelector('.book_con');
				con && (content = con.innerText.replace(/\n\n/g,'\n'));
				var h2 = a.querySelector('h2');
				h2 && (title = h2.childNodes[1].nodeValue);
			}
			return {title:title,content:content};
		});
		console.log(obj.title);
		fs.write(target,obj.title+"\n"+obj.content+"==============================================================\n",'a');
		// this.cache.chapterMap[url] = obj;
	});
}

casper.run(recurve);
